from django.shortcuts import render, redirect
from django import forms
from django.utils.timezone import now

from app01.models import Users


class LoginForm(forms.Form):
    employeeid = forms.CharField(
        label='工号',
        widget=forms.TextInput(attrs={"class": "form-control"}),
        required=True  # 错误返回后会保留
    )
    password = forms.CharField(
        label='密码',
        widget=forms.PasswordInput(attrs={"class": "form-control"}),
        required=True  # 错误返回后会保留
    )


# 登录
def login(request):
    if request.method == 'GET':
        form = LoginForm()
        return render(request, 'login.html', {'form': form})

    # 登录提交后，进入用户校验页面
    form = LoginForm(data=request.POST)
    if form.is_valid():
        # 验证成功
        u = Users.objects.filter(**form.cleaned_data).first()
        # print(form.cleaned_data['employeeid'])
        # u = Users.objects.filter(employeeid=form.cleaned_data['employeeid'], password=form.cleaned_data['password']).first()

        if u:
            # print(u)
            # 保存登录信息
            request.session['info'] = {
                'employeeid': u.employeeid,
                'name': u.name,
                'admin':u.admin
            }
            u.login_time = now
            u.save()
            return redirect('/contract/year/list/')
        else:
            form.add_error('password', '用户名或密码错误！')
    return render(request, 'login.html', {'form': form})


# 注销
def logout(request):
    request.session.clear()
    return redirect('/')
